package com.immortal.module.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.immortal.core.module.res.ApiException;
import com.immortal.core.utils.jackson.JacksonUtil;
import com.immortal.module.security.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.Collections;
import java.util.Map;

public class OauthTokenService {
    @Autowired
    private ClientDetailsService clientDetailsService;
    @Autowired
    private AuthorizationServerTokenServices authorizationServerTokenServices;

    public Map oauthToken() {
        ClientDetails clientDetails = clientDetailsService.loadClientByClientId("app");
        if (clientDetails == null) {
            throw new ApiException("clientId不存在");
        }
        TokenRequest tokenRequest = new TokenRequest(Collections.emptyMap(), "app", Lists.newArrayList("app"), "password");
        OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
        Authentication authentication = SecurityUtils.getSubject();
        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
        OAuth2AccessToken token = authorizationServerTokenServices.createAccessToken(oAuth2Authentication);
        Map tokenMap = JacksonUtil.from(JacksonUtil.to(token), Map.class);
        return tokenMap;
    }

    public JSONObject oauthTokenJSON() {
        ClientDetails clientDetails = clientDetailsService.loadClientByClientId("app");
        if (clientDetails == null) {
            throw new ApiException("clientId不存在");
        }
        TokenRequest tokenRequest = new TokenRequest(Collections.emptyMap(), "app", Lists.newArrayList("app"), "password");
        OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
        Authentication authentication = SecurityUtils.getSubject();
        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
        OAuth2AccessToken token = authorizationServerTokenServices.createAccessToken(oAuth2Authentication);
        return JSONObject.parseObject(JacksonUtil.to(token));
    }
}
